import { createRouter, createWebHashHistory } from "vue-router";
import dashboardRoute from "./baseRoutes";
import { setBrowserTitle, getMenuList, checkUserInfo } from "./tools/tools";
import { getCookie } from "@/utils/cookie";

import NProgress from "nprogress"; // 引入 nprogress
import "nprogress/nprogress.css"; // 引入 nprogress 的样式

const routes = [
  {
    path: "/",
    name: "Root",
    redirect: "/base",
    meta: {
      title: "",
      isKeepAlive: false,
    },
  },

  {
    path: "/login",
    name: "Login",
    component: () =>
      import(/* webpackChunkName: "Login" */ "@/layouts/login/login.vue"),
    meta: {
      title: "登录",
    },
  },

  {
    path: "/logout",
    name: "Logout",
    component: () =>
      import(/* webpackChunkName: "Logout" */ "@/layouts/logout/logout.vue"),
    meta: {
      title: "退出",
    },
  },

  {
    path: "/base",
    name: "Base",
    component: () =>
      import(/* webpackChunkName: "Base" */ "@/layouts/base/base.vue"),
    redirect: "/dashboard",
    children: [...dashboardRoute],
    meta: {
      title: "基础",
    },
  },

  {
    // vue2 匹配剩余路径用 "*", vue3 用 "/:pathMatch(.*)",
    path: "/:pathMatch(.*)",
    name: "404",
    component: () =>
      import(/* webpackChunkName: "404" */ "@/layouts/404/404.vue"),
    meta: {
      title: "暂无该页面",
    },
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  // 加载所有路由
  routes,
});

router.beforeEach(async (to, _from, next) => {
  NProgress.start(); // 开始进度条

  if (!["/login", "/logout"].includes(to.path) && !getCookie("token")) {
    return next({
      path: "/login",
      replace: true,
    });
  }

  // 设置对应路由的浏览器标签标题
  setBrowserTitle(to);

  // 获取菜单
  getMenuList(to);

  // 获取用户信息
  await checkUserInfo(to);

  next();
});

// 路由变化完成时停止进度条
router.afterEach(() => {
  NProgress.done(); // 完成进度条
});

export default router;
